<template>
  <div class="app-container">
    <el-form :model="form" :rules="rules" ref="form" label-width="120px">
      <!-- 序号输入框 -->
      <el-form-item label="序号" prop="urlId">
        <el-input v-model="form.urlId" placeholder="请输入序号"></el-input>
      </el-form-item>

      <!-- 直播名称输入框 -->
      <el-form-item label="直播名称" prop="name">
        <el-input v-model="form.name" placeholder="请输入直播名称"></el-input>
      </el-form-item>

      <!-- 直播图标 -->
      <el-form-item label="直播图标" prop="image">
        <div style="display: flex; align-items: center;">
          <!-- 上传图标 -->
          <el-upload
            :action="uploadUrl"
            :headers="headers"
            :on-success="handleIconUploadSuccess"
            :on-error="handleIconUploadError"
            list-type="picture-card"
            :show-file-list="false">
            <!-- 图片回显 -->
            <img v-if="form.image" :src="form.image" alt="直播图标" style="margin-left: auto; max-width: 160px; max-height: 160px;">
          </el-upload>
          <!-- 或者填写URL -->
          <el-form-item style="margin-left: 20px; flex-grow: 1;" label="或" prop="imageUrl">
            <el-input v-model="form.image" placeholder="请输入图标URL"></el-input>
          </el-form-item>
        </div>
      </el-form-item>

      <!-- 高画质流输入框 -->
      <el-form-item label="高画质流" prop="highQualityStream">
        <el-input v-model="form.highQualityStream" placeholder="请输入高画质流地址"></el-input>
      </el-form-item>

      <!-- 高画质流密码输入框 -->
      <el-form-item label="高画质流密码" prop="highQualityPassword">
        <el-input v-model="form.highQualityPassword" placeholder="请输入密码"></el-input>
        <el-button @click="addHighQualityStream" size="small" type="success">添加</el-button>
      </el-form-item>

      <!-- 高画质流地址和密码列表 -->
      <el-table :data="form.highQualityStreams" style="width: 100%">
        <el-table-column prop="url" label="地址"></el-table-column>
        <el-table-column prop="password" label="密码"></el-table-column>
        <el-table-column label="操作">
          <template slot-scope="scope">
            <el-button size="mini" @click="removeHighQualityStream(scope.$index)" type="danger">删除</el-button>
          </template>
        </el-table-column>
      </el-table>

      <!-- 低画质流输入框 -->
      <el-form-item label="低画质流" prop="lowQualityStream">
        <el-input v-model="form.lowQualityStream" placeholder="请输入低画质流地址"></el-input>
      </el-form-item>

      <!-- 低画质流密码输入框 -->
      <el-form-item label="低画质流密码" prop="lowQualityPassword">
        <el-input v-model="form.lowQualityPassword" placeholder="请输入密码"></el-input>
        <el-button @click="addLowQualityStream" size="small" type="success">添加</el-button>
      </el-form-item>

      <!-- 低画质流地址和密码列表 -->
      <el-table :data="form.lowQualityStreams" style="width: 100%">
        <el-table-column prop="url" label="地址"></el-table-column>
        <el-table-column prop="password" label="密码"></el-table-column>
        <el-table-column label="操作">
          <template slot-scope="scope">
            <el-button size="mini" @click="removeLowQualityStream(scope.$index)" type="danger">删除</el-button>
          </template>
        </el-table-column>
      </el-table>

      <!-- 直播分类多选框 -->
      <el-form-item label="直播分类" prop="categories">
        <el-checkbox
          v-for="item in categories"
          :label="item.typeId"
          :key="item.typeId"
          v-model="item.checked"
        >
          {{ item.typeName }}
        </el-checkbox>

      </el-form-item>

      <!-- 直播类型下拉框 -->
      <el-form-item label="直播类型" prop="liveStream">
        <el-select v-model="form.liveStream">
          <el-option
            v-for="dict in dict.type.live_stream"
            :key="dict.value"
            :label="dict.value"
            :value="dict.label"
          />
        </el-select>
        <span class="el-form-item__hint">注意：当选择'维修'时，终端上会隐藏此频道。</span>
      </el-form-item>

      <!-- 保存按钮 -->
      <el-form-item>
        <el-button type="primary" @click="submitForm">保存</el-button>
        <el-button @click="cancel">取消</el-button>
      </el-form-item>
    </el-form>
  </div>
</template>

<script>
import {getLive, getLiveListType, listLive, updateLive} from "@/api/media/live/list";
import { listLiveType } from "@/api/media/live/type/list";
import CryptoJS from 'crypto-js';

// 导入 AES 加密算法，mode，padding
import 'crypto-js/aes';
import 'crypto-js/mode-ecb';
import 'crypto-js/pad-pkcs7';
import {getToken} from "@/utils/auth";

export default {
  dicts: ['live_stream'],
  name: "LiveEdit",
  data() {
    return {
      uploadUrl: process.env.VUE_APP_BASE_API + "/common/upload", // 获取环境变量中的API基础路径
      headers: {
        Authorization: "Bearer " + getToken() // 设置请求头，若依通常需要Token验证
      },
      form: {
        id: "",
        urlId: "",
        name: "",
        image: "",
        highQualityStream: "",
        highQualityPassword: "",
        highQualityStreams: [],
        lowQualityStream: "",
        lowQualityPassword: "",
        lowQualityStreams: [],
        liveStream: "",
        categories: []
      },
      categories: [],
      rules: {
        urlId: [{ required: true, message: '序号不能为空', trigger: 'blur' }],
        name: [{ required: true, message: '直播名称不能为空', trigger: 'blur' }],
      }
    };
  },
  created() {
    this.getList();
    const id = this.$route.params.id;
    this.getLiveDetails(id);
    this.getEditType(id);
  },
  methods: {
    getList() {
      this.loading = true;
      listLiveType().then(response => {
        this.categories = response.rows.map(item => ({
          ...item,
          checked: false
        }));
        this.total = response.total;
        this.loading = false;
      });
    },

    getEditType(id) {
      this.loading = true;
      getLiveListType(id).then(response => {
        let selectedCategoryIds = response.data;
        console.log(selectedCategoryIds, 'selectedCategoryIds');

        // 确保 selectedCategoryIds 是数组
        if (!Array.isArray(selectedCategoryIds)) {
          selectedCategoryIds = []; // 如果不是数组，设置为空数组
        }

        // 确保 categories 已经是数组
        if (!Array.isArray(this.categories)) {
          this.categories = [];
        }

        // 更新每个类别的 `checked` 状态
        this.categories.forEach(item => {
          // 检查 selectedCategoryIds 是否包含当前类别的 typeId
          item.checked = selectedCategoryIds.some(category => category.typeId === item.typeId);
          console.log(item.checked, 'item.checked');
        });

        // 更新 form.categories
        this.form.categories = this.categories.filter(item => item.checked).map(item => item.typeId);
        console.log(this.form.categories, 'this.form.categories');

        this.loading = false;
      }).catch(error => {
        this.loading = false;
        console.error('获取直播类型失败:', error);
      });
    },

    getLiveDetails(id) {
      getLive(id)
        .then(response => {
          this.form = response.data;
          this.form.liveStream = String(this.form.liveStream);

          const decryptedPassword = this.decryptPassword(this.form.password || '', 'TP25076786123456');
          const decryptedUrl = this.decryptUrl(this.form.url, 'TP25076786123456');

          // 使用增强型正则表达式分割粘连的流信息
          const urlRegex = /(hd\d+|sd\d+):(.*?)(?=(hd\d+|sd\d+):|$)/gs;
          const passwordRegex = /(hd\d+|sd\d+):(\d+)/g;

          // 解析 URL
          const urlMatches = [];
          let urlMatch;
          while ((urlMatch = urlRegex.exec(decryptedUrl)) !== null) {
            urlMatches.push({
              type: urlMatch[1],
              url: urlMatch[2].trim()
            });
          }

          // 解析密码
          const passwordMap = new Map();
          let passwordMatch;
          while ((passwordMatch = passwordRegex.exec(decryptedPassword)) !== null) {
            passwordMap.set(passwordMatch[1], passwordMatch[2]);
          }

          // 分类处理
          const highQualityStreams = [];
          const lowQualityStreams = [];

          urlMatches.forEach(({ type, url }) => {
            const stream = {
              url: url.replace(/(hd\d+|sd\d+):/, ''), // 二次清理可能残留的类型标识
              password: passwordMap.get(type)
            };

            type.startsWith("hd")
              ? highQualityStreams.push(stream)
              : lowQualityStreams.push(stream);
          });

          this.form.highQualityStreams = highQualityStreams;
          this.form.lowQualityStreams = lowQualityStreams;
        })
        .catch(error => {
          console.error('获取直播频道详情失败:', error);
        });
    },

    decryptUrl(encryptedUrl, password) {
      try {
        const key = CryptoJS.enc.Utf8.parse(password);
        const encryptedUrlParts = encryptedUrl.split(',');  // 保留逗号进行分割

        const decryptedUrlParts = encryptedUrlParts.map(part => {
          const encryptedBytes = CryptoJS.enc.Base64.parse(part);
          const decryptedBytes = CryptoJS.AES.decrypt({ ciphertext: encryptedBytes }, key, {
            mode: CryptoJS.mode.ECB,
            padding: CryptoJS.pad.Pkcs7,
          });

          const decryptedText = decryptedBytes.toString(CryptoJS.enc.Utf8);

          if (!decryptedText) {
            return decryptedBytes.toString(CryptoJS.enc.Base64);
          }

          return decryptedText;
        });

        return decryptedUrlParts.join(',');  // 返回逗号分隔的字符串
      } catch (e) {
        return '';
      }
    },

    decryptPassword(encryptedPassword, password) {
      try {
        const key = CryptoJS.enc.Utf8.parse(password);
        const encryptedPasswordParts = encryptedPassword.split(',');  // 保留逗号进行分割

        const decryptedPasswordParts = encryptedPasswordParts.map(part => {
          const encryptedBytes = CryptoJS.enc.Base64.parse(part);
          const decryptedBytes = CryptoJS.AES.decrypt({ ciphertext: encryptedBytes }, key, {
            mode: CryptoJS.mode.ECB,
            padding: CryptoJS.pad.Pkcs7,
          });

          const decryptedText = decryptedBytes.toString(CryptoJS.enc.Utf8);

          if (!decryptedText) {
            return decryptedBytes.toString(CryptoJS.enc.Base64);
          }

          return decryptedText;
        });

        return decryptedPasswordParts.join(',');  // 返回逗号分隔的字符串
      } catch (e) {
        return '';
      }
    },

    submitForm() {
      this.$refs["form"].validate(valid => {
        if (valid) {
          this.$modal.loading("正在提交表单")
          this.form.categories = this.categories
            .filter(item => item.checked)
            .map(item => item.typeId);

          const data = {
            id: this.form.id,
            name: this.form.name,
            image: this.form.image,
            highLiveStreamList: this.form.highQualityStreams,
            lowLiveStreamList: this.form.lowQualityStreams,
            typeId: this.form.categories,
            urlId: this.form.urlId,
            liveStream: this.form.liveStream
          };

          updateLive(data).then(response => {
            this.$modal.msgSuccess("直播更新成功");
          }).finally(()=>{
            this.$modal.closeLoading()
            this.$router.go(-1)
          }).catch(error => {
            console.error('更新直播失败:', error);
          });
        }
      });
    },

    cancel() {
      this.$router.go(-1);
    },

    addHighQualityStream() {
      if (this.form.highQualityStream.startsWith('http://') || this.form.highQualityStream.startsWith('https://')) {
        this.form.highQualityStreams.push({
          url: this.form.highQualityStream,
          password: this.form.highQualityPassword
        });
        this.form.highQualityStream = "";
        this.form.highQualityPassword = "";
      } else {
        alert("无效流地址");
      }
    },

    removeHighQualityStream(index) {
      this.form.highQualityStreams.splice(index, 1);
    },

    addLowQualityStream() {
      if (this.form.lowQualityStream.startsWith('http://') || this.form.lowQualityStream.startsWith('https://')) {
        this.form.lowQualityStreams.push({
          url: this.form.lowQualityStream,
          password: this.form.lowQualityPassword
        });
        this.form.lowQualityStream = "";
        this.form.lowQualityPassword = "";
      } else {
        alert("无效流地址");
      }
    },

    removeLowQualityStream(index) {
      this.form.lowQualityStreams.splice(index, 1);
    },

    handleIconUploadSuccess(response, file, fileList) {
      this.form.image = response.url;
    },

    handleIconUploadError(err, file, fileList) {
      this.$message.error('上传失败，请稍后再试');
    },
  }
};
</script>

<style scoped>
.app-container {
  padding: 20px;
}

.el-form-item__hint {
  font-size: 12px;
  color: #888;
  margin-top: 5px;
  display: block;
}
</style>
